_LOG = {
  // where all requests are going to be directed eg:
  // log/fetch-last-entry
  controllerName : 'log',
  lastEntry : null,
  firstLastEntryId : null,
  fetchLastEntry : function ()
  {
    $.ajax({
      url: '/'+_LOG.controllerName+'/fetch-last-entry',
	  dataType : 'json',
	  success : function(data) {
        _LOG.lastEntry = data;

	    if (typeof data.id == 'undefined')
	      _LOG.lastEntry = { id : 0 }

		_LOG.firstLastEntryId = _LOG.lastEntry.id;
      }
    });
  },
  addRowCall : null,
  clearDataCall : null,
  liveUpdateIntervalObj : false,
  liveUpdateIntervalTime : 500,
  liveUpdateIntervalCallProcessing : false,
  liveUpdateIntervalCall : function ()
  {
    if (_LOG.liveUpdateIntervalCallProcessing) return;

	_LOG.liveUpdateIntervalCallProcessing = true;
    // get latest log entries
    $.ajax({
      url: '/'+_LOG.controllerName+'/fetch-older-than-id',
	  data : { id : _LOG.lastEntry.id, filter : $("#log-filter").val() },
	  dataType : 'json',
	  success : function(data) {
		for (i in data)
		{
	      if (_LOG.lastEntry.id < data[i].id)
	        _LOG.lastEntry = data[i];

	      if (typeof _LOG.addRowCall != 'undefined')
		    _LOG.addRowCall(data[i]);
		}
		_LOG.liveUpdateIntervalCallProcessing = false;
      }
    });
  },
  filterIntervalObj : false,
  filterIntervalTime : 500,
  filterIntervalCall : function () {
	_LOG.clearDataCall();
	_LOG.lastEntry = { id : _LOG.firstLastEntryId }
    _LOG.liveUpdateIntervalCall();
  },
  startLiveUpdate : function (addRowCall, clearDataCall)
  {
	_LOG.addRowCall = addRowCall;
	_LOG.clearDataCall = clearDataCall;
    _LOG.fetchLastEntry();

	_LOG.liveUpdateIntervalObj = setInterval(_LOG.liveUpdateIntervalCall, _LOG.liveUpdateIntervalTime);
	
	$("#log-filter").keypress(function() {
      clearTimeout(_LOG.filterIntervalObj);
      _LOG.filterIntervalObj = setTimeout(_LOG.filterIntervalCall, _LOG.filterIntervalTime);
	});
  },
}
